import { setPageTitle, pageTitleMap } from './i18n.js';

// 全局混入文件
export const languageMixin = {
  onLoad() {
    // 页面加载时确保语言设置正确
    this.initPageLanguage();
  },
  
  onShow() {
    // 页面显示时也检查语言设置
    this.initPageLanguage();
  },
  
  methods: {
    initPageLanguage() {
      const currentLang = uni.getStorageSync('app_lang');
      if (currentLang && this.$i18n.locale !== currentLang) {
        this.$i18n.locale = currentLang;
        console.log('页面语言初始化:', currentLang);
      }
    }
  }
};

// 页面标题混入
export const pageTitleMixin = {
  onLoad() {
    // 设置页面标题
    this.setPageTitle();
  },
  
  methods: {
    setPageTitle() {
      // 获取当前页面路径
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const route = currentPage.route;
      
      // 根据路由设置标题
      const pageKey = pageTitleMap[route];
      if (pageKey) {
        setPageTitle(pageKey);
      } else {
        // 如果没有找到映射，尝试使用页面名称作为key
        const pageName = route.split('/').pop();
        if (pageName && pageName !== 'index') {
          // 尝试直接设置标题
          const currentLang = uni.getStorageSync('language') || 'zh';
          const messages = currentLang === 'zh' ? this.$i18n.messages.zh : this.$i18n.messages.en;
          const title = messages.pageTitles?.[pageName];
          if (title) {
            uni.setNavigationBarTitle({
              title: title
            });
          }
        }
      }
    }
  }
};

// 导出混入
export default {
  languageMixin,
  pageTitleMixin
}; 